<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="media-src 'self' file: data: blob: filesystem:; media-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'"/>
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>B站直播保安室监控</title>
  </head>
  <body>
    <div class="headdiv">
      <input id="headinp" placeholder="直播间号">
      <button class="headbtn" onclick="headbtnClick()">添加</button>
    </div>
    <div id="roomdivs"></div>
    <script>
      var roomdivs = document.getElementById('roomdivs')
      var roomList = []
      var fs = require('fs')
      fs.readFile("bilibili-tv.json", 'utf-8', function (err, data) {
          if (err) {
            console.log("An error occurred reading the file :" + err.message)
              return
          }
          console.log("The file content is : " + data)
          roomList = JSON.parse(data).roomList
          console.log(roomList)
          clock()
      })
      function headbtnClick() {
        var roomid = document.getElementById('headinp').value
        getroomdata("https://api.live.bilibili.com/room/v1/Room/room_init?id="+roomid)
      }

      var int=self.setInterval("clock()",30000);
      function clock()
      {
        for (let index = 0; index < roomList.length; index++) {
          var roomdata = roomList[index];
          getroomdata("https://api.live.bilibili.com/room/v1/Room/room_init?id="+roomdata.room_id)
        }
      }

      function lodroom(roomdata) {
        var roomdiv = ''
        try {
          roomdiv = document.getElementsByClassName(roomdata.room_id+"roomdiv")
          if (roomdiv.length <= 0) {
            makeroomdev(roomdata)
          }else{
            var roombtn = document.getElementsByClassName(roomdata.room_id+"roombtn")[0]
            if (roomdata.live_status === 0) {
              roombtn.className = 'redbtn '+ roomdata.room_id+'roombtn'
              console.log(roomdata.room_id+'Touch Fish')
            }else{
              roombtn.className = 'greenbtn '+ roomdata.room_id+'roombtn'
              console.log(roomdata.room_id+'Living')
            }
          }
        } catch (error) {
          makeroomdev(roomdata)
        }
      }

      function makeroomdev(roomdata) {
        roomdiv = document.createElement("div")
        roomdiv.className = 'roomdiv '+roomdata.room_id+"roomdiv"
        var roomlable = document.createElement("lable")
        var roombtn = '<button class="'
        roomlable.innerText = roomdata.uname
        roomlable.className = 'roomlable '+roomdata.room_id+"roomlable"
        if (roomdata.live_status === 0) {
          roombtn = roombtn + 'redbtn ' + roomdata.room_id+'roombtn"'
        }else{
          roombtn = roombtn + 'greenbtn ' + roomdata.room_id+'roombtn"'
        }
        roombtn = roombtn+' onclick="roombtnc('+roomdata.room_id+')">Live</button>'
        roomdiv.innerHTML = roombtn
        roomdiv.appendChild(roomlable)
        roomdivs.appendChild(roomdiv)
        var p = true
        for (let index = 0; index < roomList.length; index++) {
          const element = roomList[index];
          if (element.room_id === roomdata.room_id) {
            p = false
          }
        }
        if (p) {
          roomList.push(roomdata)
          var setting = {
          roomList: roomList
          }
          setting = JSON.stringify(setting)
          fs.writeFile("bilibili-tv.json", setting, function (err) {
              if (err) {
                  console.log("An error occurred creating the file " + err.message)
              } else {
                  console.log("The file has been successfully saved")
              }
          })
        }
      }

      function getroomname(roomdata) {
        var httpRequest = new XMLHttpRequest()//第一步：创建需要的对象
        httpRequest.open('GET','https://live.bilibili.com/'+roomdata.room_id, true) //第二步：打开连接
        httpRequest.setRequestHeader("Content-type","application/json");//设置请求头
        httpRequest.send()//发送请求
        /**
         * 获取数据后的处理程序
         */
        httpRequest.onreadystatechange = function () {//请求后的回调接口，可将请求成功后要执行的程序写在其中
            if (httpRequest.readyState == 4 && httpRequest.status == 200) {//验证请求是否发送成功
                var roomhtml = httpRequest.responseText//获取到服务端返回的数据
                var str = roomhtml.match(/{"uname":"(.*?)"/)[0];
                if (str === undefined || str === null || str === '') {
                  roomdata.uname = roomdata.room_id
                  lodroom(roomdata)
                }else{
                  roomdata.uname = str.replace('{"uname":"','')
                  roomdata.uname = roomdata.uname.replace('"','')
                  lodroom(roomdata)
                }
            }
        }
      }

      function getroomdata(url) {
        var httpRequest = new XMLHttpRequest()//第一步：创建需要的对象
        httpRequest.open('GET', url, true) //第二步：打开连接
        httpRequest.setRequestHeader("Content-type","application/json");//设置请求头
        httpRequest.send()//发送请求
        /**
         * 获取数据后的处理程序
         */
        httpRequest.onreadystatechange = function () {//请求后的回调接口，可将请求成功后要执行的程序写在其中
            if (httpRequest.readyState == 4 && httpRequest.status == 200) {//验证请求是否发送成功
                var json = JSON.parse(httpRequest.responseText);//获取到服务端返回的数据
                if (json.code === 0) {
                  getroomname(json.data)
                }else{
                  window.alert(JSON.stringify(json));
                }
            }
        }
      }

      function roombtnc(id) {
        var ym = 'live.html?id='+id
        window.open (ym,id,'height=270,width=600,frame=false')
      }
		</script>
  </body>
  <style>
    html,body{
      height: 100%;
      margin: 0;
      background-color:black;
    }
    button{
      float: right;
    }
    .headdiv{
      width: 100%;
      height: 5%;
      background-color: black;
      float: top;
    }
    #headinp{
      height: 100%;
      width: 70%;
      margin: 0;
      border: 0;
      padding: 0;
    }
    .headbtn{
      height: 100%;
      width: 30%;
      margin: 0;
      border: 0;
      padding: 0;
    }
    #roomdivs{
      height: 95%;
      width: 100%;
      background-color: black;
    }
    .roomdiv{
      width: 100%;
    }
    .greenbtn{
      background-color: darkseagreen;
      height: 100%;
      float: right;
      
    }
    .redbtn{
      background-color: brown;
      height: 100%;
      float: right;
    }
    .roomlable{
      color: rgb(255, 255, 255);
    }
  </style>
</html>
